import re

from django.db import models
from django.utils.translation import ugettext_lazy as _

import app_settings

DEFAULT_MAINTENANCE_WHITE_LIST = """
/admin/.*
/media/.*
/admin_media/.*
"""

class SetupManager(models.Manager):
    def get_current(self):
        try:
            return self.get_query_set().get(enabled=True)
        except Setup.DoesNotExist, e:
            return self.create(name='Default', enabled=True)

class Setup(models.Model):
    """This model class allows you have more than one setup for dynamic 
    functions in one project."""

    name = models.CharField(max_length=30)

    # Sets this setup as the enabled one
    enabled = models.BooleanField(default=False, blank=True)

    # Sets the site is in maintanance state
    maintenance_state = models.BooleanField(default=False, blank=True)
    maintenance_white_list = models.TextField(default=DEFAULT_MAINTENANCE_WHITE_LIST, blank=True)

    objects = SetupManager()
    
    def __unicode__(self):
        return self.name

    def in_maintenance_white_list(self, path):
        for item in self.maintenance_white_list.split('\n'):
            if not item.strip(): continue

            if re.match(item.strip(), path, re.I):
                return True

        return False

    class Meta:
        ordering = ('id',)
        verbose_name_plural = 'Setup'
        permissions = (
                ('can_access',_('Can access Dynamic Manager')),
                ('can_manage_files',_('Can manage File Manager')),
                ('can_access_sql_monitor',_('Can access SQL Monitor')),
                ('can_use_sql_shell',_('Can use SQL Shell')),
                ('can_manage_repository',_('Can manage Repository')),
                )

"""
Signals and Listeners
"""
from django.db.models import signals

# Setup

def setup_post_save(sender, instance, signal, *args, **kwargs):
    "Disable others"
    if instance.enabled:
        for setup in Setup.objects.filter(enabled=True).exclude(id=instance.id):
            setup.enabled = False
            setup.save()

signals.post_save.connect(setup_post_save, sender=Setup)
